﻿$(document).ready(function() {
    $(window).load(function() {
        LoadRuleOptions();
        $('#txtOverDisc').prop({
            "disabled": "disabled",
            "checked": false
        });
    });

    $('#cbAddRules').change(function() {
        var sendval = $(this).val();
        if (!(sendval == "0" || sendval == 0)) {
            var attrChk = (sendval == 'CH' || sendval == 'DC') ? "disabled" : false;
            $('#txtOverDisc').attr({
                "checked": false,
                "disabled": attrChk
            });

            $.ajax({
                type: "POST",
                url: 'AddRules.aspx/RuleFormula',
                data: '{"RulePrefix": "' + sendval + '"}',
                contentType: "application/json;charset=utf-8",
                datatype: "json",
                success: function(data) {
                    processRules(data.d);
                }
            });
            return false;
        } else {
            $('#divCondition').html("");
            $('#txtOverDisc').attr({
                "checked": false,
                "disabled": true
            });
        }
    });

    $('#txtOverDisc').change(function() {
        var setval = $('#txtFixDisc');
        var iState = $(this).prop("checked");
        if (iState == true) {
            var divParent = $('#divCondition').children();
            var divParentLen = divParent.length;
            if (divParentLen > 1) {
                var divChild = divParent.eq(1).children().eq(1).children();
                var divChVal = divChild.val();
                if (!(divChVal == '=')) {
                    alert('Discount must be set equal sign (=) to force overridding!');
                    $(this).prop('checked', false);
                } else {
                    setval.val("1");
                }
            }
        } else {
            setval.val("0");
        }
    });

    $('#divCondition').on('change', '.txtCH, .txtOpt', function() {
        var tblTarget = $('#tblAddRule > tbody');
        var prefix = $('#cbAddRules').val();
        var optval = $('.txtOpt');
        var sign1 = "";
        var sign2 = "";

        var optLen = $('.txtOpt').length;
        if (optLen > 1) {
            sign1 = optval.eq(0).val();
            sign2 = optval.eq(1).val();
            if (!(sign2 == '=')) {
                $('#txtOverDisc').prop("checked", false);
            }
        } else {
            sign1 = optval.val();
        }

        var strData = '{"RulePrefix": "' + prefix + '", ';
        strData += '"Operator1": "' + sign1 + '", ';
        strData += '"Operator2": "' + sign2 + '"}';
        $.ajax({
            type: "POST",
            url: 'AddRules.aspx/RuleDetails',
            data: strData,
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function(data) {
                if (data.d.length > 0) {
                    var ruleName = data.d[0];
                    var totalRules = data.d[1];
                    tblTarget.children('tr').eq(4).children('td').eq(2).text(ruleName);
                    tblTarget.children('tr').eq(4).children('td').eq(0).find('input:hidden').val(ruleName);
                    tblTarget.children('tr').eq(5).children('td').eq(2).text(totalRules);
                }
            }
        });
        return false;
    });

    $('#' + form1).submit(function(e) {
        e.preventDefault();
        /*
        $('#divRules').html("").hide(function() {
        var ruleTree = createLayers(5);
        $('#rule-wrapper').html(ruleTree);
        $('#divLayerEditor').fadeIn(300);
        });
        */
        var errMsg = "";
        var isErr = true;
        var arrFields = $(this).serializeArray();
        var arrLen = arrFields.length;
        for (var i = 1; i < (arrLen - 2); i++) {
            var chkval = arrFields[i].value;
            if (!(arrFields[i].name == 'txtOverDisc')) {
                if (!(typeof chkval == 'undefined' || chkval == '' || chkval == 0 || chkval == '0')) {
                    isErr = false;
                } else {
                    isErr = true;
                    break;
                }
            }
        }

        if (isErr == false) {
            var _ruleControl = $('#cbAddRules').val();
            var _ruleCategory = $('#txtCategory').val();
            var _tmpDescription = $('#txtDescription').val();
            var _tmpRuleOverride = $('#txtFixDisc').val();
            var _ruleOverride = (parseInt(_tmpRuleOverride) > 0) ? _tmpRuleOverride : 0;
            var _tmpKeyLayer = $('#txtAppKey').val();
            var _ruleKeyLayer = (typeof _tmpKeyLayer == 'undefined' || _tmpKeyLayer == '' || isNaN(_tmpKeyLayer)) ? '' : _tmpKeyLayer;
            if (_ruleKeyLayer == '') {
                alert('Invalid Number Format for Approval Key Layer!');
                return false;
            } else if (_ruleKeyLayer < 1) {
                alert('Approval Key Layer must be higher than 1!');
                return false;
            }

            var _tmpMaxLayer = $('#txtLayers').val();
            var _ruleMaxLayer = (typeof _tmpMaxLayer == 'undefined' || _tmpMaxLayer == '' || isNaN(_tmpMaxLayer)) ? '' : _tmpMaxLayer;
            if (_ruleMaxLayer == '') {
                alert('Invalid Number Format for Total Approval Layers (Max)!');
                return false;
            } else if (_ruleMaxLayer < _ruleKeyLayer) {
                alert('Total Approval Layers (Max) must be higher than Approval Key Layer!');
                return false;
            }
            var _ruleDescription = (typeof _tmpDescription == 'undefined' || _tmpDescription == '') ? '' : _tmpDescription;

            var divConditions = $('#divCondition');
            var divSubConds = divConditions.children();
            var condsLen = divSubConds.length;

            var subConds = [];
            var optsym = [];
            var optval = [];
            for (var idx = 0; idx < condsLen; idx++) {
                var _optsym = divSubConds.eq(idx).children().eq(1).find('.txtOpt').val();
                var _optval = divSubConds.eq(idx).children().eq(2).find('.txtCH').val();
                optsym.push(_optsym);
                optval.push(_optval);
            }

            subConds[0] = _ruleControl;
            subConds[1] = _ruleCategory;
            subConds[2] = _ruleDescription;
            subConds[3] = _ruleKeyLayer;
            subConds[4] = _ruleMaxLayer;
            subConds[5] = _ruleOverride;

            var ruleval = [];
            ruleval[0] = optsym;
            ruleval[1] = optval;
            var _NewRule = '{"RuleParams": ["' + subConds + '"], ';
            _NewRule += '"Operator": ["' + optsym + '"], ';
            _NewRule += '"OptValue": ["' + optval + '"]}';

            $.ajax({
                type: "POST",
                url: 'AddRules.aspx/CreateRule',
                data: _NewRule,
                contentType: "application/json;charset=utf-8",
                datatype: "json",
                success: function(data) {
                    if (data.d[0] == 'success') {
                        $('#divRules').html("").hide(function() {
                            var cacheInfo = cacheData(data.d[1]);
                            var ruleTree = createLayers(_ruleMaxLayer);

                            $('#divCache').html(cacheInfo);
                            $('#rule-wrapper').html(ruleTree);
                            $('#divLayerEditor').fadeIn(300);
                        });
                    } else {
                        alert(data.d[1]);
                    }
                }
            });
            return false;

        } else {
            alert('Create new rule failed!' + "\n" + 'Please fill all required fields.');
        }

    });

    $('#imgInfo1').click(function() {
        var txtTitle = 'Approval Layer Key';
        var txtBody = '<p>Layer number where the approval path should be created.</p>';
        txtBody += '<strong>Note:</strong><br />';
        txtBody += 'This Layer Key can be used as an information or guide in creating approval path ';
        txtBody += 'whenever make any changes in Approval Layer Editor.';

        createHelp(txtTitle, txtBody, 254, 300);
    });

    $('#imgInfo2').click(function() {
        var txtTitle = 'Total Approval Layers (Max)';
        var txtBody = '<p>This will create numbers of approval layers in layer editor.</p>';
        txtBody += '<strong>Note:</strong><br />';
        txtBody += 'System will automatically create <strong>N</strong> initial ' +
            'amount of layers in layer editor. ';
        txtBody += 'The total layer numbers will automatically changed when ' +
            'you add new layers in Approval Layer Editor.';

        createHelp(txtTitle, txtBody, 266, 300);
    });

    $('#imgInfo3').click(function() {
        var txtTitle = 'Override Discount';
        var txtBody = '<p>This option can only be activated if <strong>Rule Control</strong> is set to ' +
            'a combination of Channel + Discount with equal sign operator (=) on discount field.<br /><br />' +
            'Whenever user create new request and the condition is met, then ' +
            'system will automatically fill discount to fixed amount for all products.</p>';
        txtBody += '<strong>Note:</strong><br />' +
            'This rule can not be created if there is another rule which have been created previously ' +
            'with the same Channel\'s Name.<br /><br />' +
            'User will not be able to enter the discount manually, system will lock the discount field ' +
            'on new request with this rule category.';

        createHelp(txtTitle, txtBody, 330, 420);
    });

    $('.btnHelp').click(function() {
        var txtTitle = 'CREATE NEW APPROVAL RULE /<br />ADD SCENARIO';
        var txtBody = '<p>This page can be used either to create a brand new rule or add scenario ' +
            'from existing rule. To create new rule, make sure that you create a valid rule which is not ' +
            'opposite to any existing rules.</p>';
        txtBody += '<p>To add new scenario, just simply choose the same Rule ' +
            'Control and Conditions to previous created rule. The system will automatically add the new ' +
            'scenario to any matching rules which has been created before.</p>';

        createHelp(txtTitle, txtBody, 300, 360);
    });

    $('#btnSave').click(function() {
        $('#' + form1).submit();
    });

    $('#btnCancel').click(function() {
        window.location.href = "ApprovalRule.aspx";
    });

    $('#btnAddLayer').click(function() {
        var layerParent = $('#rule-wrapper');
        var layerRuleBox = layerParent.children('.rule-box');
        var layerLength = layerRuleBox.length;
        var arrowDown = layerRuleBox.eq((layerLength - 1)).children().eq(1);
        arrowDown.show();

        var newLayer = addLayer(layerLength);
        $('#rule-wrapper').append(newLayer);

        var gotoDiv = layerRuleBox.eq((layerLength - 1));
    });

    $('#rule-wrapper').on('click', '.btnRemoveLayer', function() {
        var topParent = $('#rule-wrapper').children('.rule-box');
        var topParentLength = topParent.length;
        var thisParent = $(this).parent().parent();
        var getLength = thisParent.index();
        var prevArrow = $('#rule-wrapper').children('.rule-box').eq((getLength - 1)).children('.ruleDown');
        topParent.eq(getLength).remove();
        if ((getLength - 1) >= 1 && topParentLength == (getLength + 1)) {
            prevArrow.hide();
        }
        var newLength = topParentLength - 1;
        if (newLength > 2) {
            var newIdx = 1;
            for (var idx = 2; idx < (newLength + 1); idx++) {
                var newTitle = 'Approval Layer: ';
                var ctrlBox = topParent.eq(idx).children().children().eq(0).children().eq(0);
                var isVisible = ctrlBox.is(":visible");
                if (isVisible) {
                    newIdx++;
                    newTitle += newIdx;
                } else {
                    continue;
                }
                ctrlBox.text(newTitle);
            }
        }
    });

    $('#rule-wrapper').on('click', '.btnAdd', function() {
        var thisParent = $(this).parentsUntil('div#rule-wrapper').eq(2);
        var thisIndex = thisParent.index();
        var cbAdd = $(this).next();
        var strFindBy = cbAdd.val();

        if (strFindBy == 1) {
            var strData = '{"Search": ""}';
            var postTo = "AddRules.aspx/LoadRole";
            $.ajax({
                type: "POST",
                url: postTo,
                data: '{"Search": ""}',
                contentType: "application/json;charset=utf-8",
                datatype: "json",
                success: function(data) {
                    var content = processJSON(data.d, thisIndex);
                    if (typeof content != 'undefined' || content != '') {
                        dialogForm(strFindBy, thisIndex, content);
                        $("#ModalDialog").showCZDialog({
                            width: 400,
                            height: 350
                        });
                    }
                }
            });
            return false;
        } else {
            dialogForm(strFindBy, thisIndex);
            $("#ModalDialog").showCZDialog({
                width: 400,
                height: 350
            });
        }
    });

    $('#ModalDialog').on('keypress', '#autocomplete1', function(e) {
        if (e.keyCode == 13) {
            var thisParent = $(this).parent();
            var tmpVal = $(this).val();
            if (typeof tmpVal == 'undefined' || tmpVal == '') {
                alert('Please type keywords!');
                return false;
            } else {
                searchData(thisParent, tmpVal);
            }
        }
    });

    $('#ModalDialog').on('click', '#btnSearch', function() {
        var thisParent = $(this).parent();
        var tmpVal = $(this).prev().val();
        if (typeof tmpVal == 'undefined' || tmpVal == '') {
            alert('Please type keywords!');
            return false;
        } else {
            searchData(thisParent, tmpVal);
        }
    });

    $('#rule-wrapper').on('click', '.imgDel', function() {
        var thisRow = $(this).closest('tr');
        var thisParent = thisRow.parent();
        thisRow.remove();
        var countRows = thisParent.children('tr').length;
        if (countRows > 0) {
            for (var idx = 0; idx < (countRows); idx++) {
                var addOddEven = ((idx % 2) == 0) ? 'odd' : 'even';
                thisParent.children('tr').eq(idx).attr("class", addOddEven);
            }
        } else {
            thisParent.append('<tr><td colspan="3">No data</td></tr>');
        }
    });

    $('#btnUpdateLayer').click(function() {
        var question = "Do you want to update rule?";
        if (confirm(question) == true) {
            var sData = [];
            sData[0] = $('#txtCtrlEnd').val();
            sData[1] = $('#txtValEnd').val();
            sData[2] = $('#txtValExtEnd').val();
            sData[3] = $('#txtPathEnd').val();

            saveLayer(sData);
        }
    });

});

function createHelp(helpTitle, helpText, helpHeight, helpWidth) {
    //closeButton: '#btnClosePop'
    var dTitle = '<div style="border-bottom:1px dotted #000;padding:5px 0;font-size:14px;font-weight:bold;margin:10px;text-align:center;font-family:Arial">' + 
        helpTitle + '</div>';
    var dContent = '<div style="font-size:12px;padding:0;margin:0 10px;color:#007FFF;">' + 
        helpText + '</div>';
    var dButton = '<div id="closeHelpWrapper" style="position:absolute;bottom:10px;left:0;width:100%;text-align:center;">' + 
        '<div id="closeHelp" class="btnSmall">Close</div>' +
        '</div>';
    var helpContent = dTitle + dContent + dButton;

    $('#ModalDialog').html(helpContent).showCZDialog({
        width: helpWidth, height: helpHeight, closeButton: '#closeHelp'
    });
    $('#divModalWrap').css("background", "#FFF");
}

function processRules(data) {
    var tblTarget = $('#tblAddRule > tbody');
    tblTarget.children('tr').eq(4).children('td').eq(2).text("");
    tblTarget.children('tr').eq(5).children('td').eq(2).text("");
    
    var divTarget = $('#divCondition');
    
    var ctrls = data.Controls;
    var opts = data.Operators;
    var ctns = data.Contents;
    var ctrlsLen = ctrls.length;
    var ctnsLen = ctns.length;

    var txtCHBox = '<input type="text" name="txtCH[]" class="txtCH" value="" maxlength="5" style="padding:0;width:42px;font-size:12px;text-align:right;" /> ';
    //txtCHBox += '<span style="color:Red;">*</span>';
    txtCHBox += '<span>%</span>';
    var txtCH = [];
    if (ctnsLen > 0) {
        var tmpCH = '<select name="txtCH[]" class="txtCH" style="font-size:12px;">';
        tmpCH += '<option value="0">--- Select ---</option>';
        for (var idxCH = 0; idxCH < ctnsLen; idxCH++) {
            var ctnsID = ctns[idxCH].ID;
            var ctnsVal = ctns[idxCH].CHName;
            var tmpOptCH = '<option value="' + ctnsID + '">';
            tmpOptCH += ctnsVal + '</option>';

            tmpCH += tmpOptCH;
        }
        tmpCH += '</select>';

        txtCH.push(tmpCH);
        txtCH.push(txtCHBox);
    } else {
        txtCH[0] = txtCHBox;
    }
    
    var tblRows = '';
    if (ctrlsLen > 1) {
        for (var idx1 = 0; idx1 < ctrlsLen; idx1++) {
            var txtSym = '<select name="txtOpt[]" class="txtOpt" style="font-size:12px; width:42px;">';

            var tmpOptSplit = opts[idx1].split(',');
            var tmpOptSplitLen = tmpOptSplit.length;
            if (tmpOptSplitLen > 1) {
                for (var idxOpt = 0; idxOpt < tmpOptSplitLen; idxOpt++) {
                    var tmpOptSym = '<option value="' + tmpOptSplit[idxOpt] + '">';
                    tmpOptSym += tmpOptSplit[idxOpt] + '</option>';

                    txtSym += tmpOptSym;
                }
            } else {
                txtSym += '<option value="' + tmpOptSplit[0] + '">' + tmpOptSplit[0] + '</option>';
            }
            txtSym += '</select>';

            var tmpRow = '<div class="divSubCon"><div class="fl_left" style="margin-right:5px; width:60px; padding-top:1px;">' + ctrls[idx1] + ' <span style="color:Red;">*</span></div>';
            tmpRow += '<div class="fl_left" style="margin-right:5px;">' + txtSym + '</div>';
            tmpRow += '<div class="fl_left" style="margin-bottom:5px;">' + txtCH[idx1] + '</div>';
            tmpRow += '<div class="cl_left"></div></div>';

            tblRows += tmpRow;
        }
    } else {
        var txtSym = '<select name="txtOpt[]" class="txtOpt" style="font-size:12px; width:42px;">';

        var tmpOptSplit = opts[0].split(',');
        var tmpOptSplitLen = tmpOptSplit.length;
        if (tmpOptSplitLen > 1) {
            for (var idxOpt = 0; idxOpt < tmpOptSplitLen; idxOpt++) {
                var tmpOptSym = '<option value="' + tmpOptSplit[idxOpt] + '">';
                tmpOptSym += tmpOptSplit[idxOpt] + '</option>';

                txtSym += tmpOptSym;
            }
        } else {
            txtSym += '<option value="' + tmpOptSplit[0] + '">' + tmpOptSplit[0] + '</option>';
        }
        txtSym += '</select>';

        var tmpRow = '<div class="divSubCon"><div class="fl_left" style="margin-right:5px; width:60px; padding-top:1px;">' + ctrls[0] + ' <span style="color:Red;">*</span></div>';
        tmpRow += '<div class="fl_left" style="margin-right:5px;">' + txtSym + '</div>';
        tmpRow += '<div class="fl_left" style="margin-bottom:5px;">' + txtCH[0] + '</div>';
        tmpRow += '<div class="cl_left"></div></div>';

        tblRows += tmpRow;
    }

    divTarget.html(tblRows);
}

function LoadRuleOptions(){
    $.ajax({
        type: "POST",
        url: 'AddRules.aspx/LoadRules',
        data: '{}',
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            //console.log(data.d);
            var dLen = data.d.length;
            var optList = '<option value="0">---Select---</option>';
            for (var idx = 0; idx < dLen; idx++) {
                var optKey = data.d[idx].RuleCode;
                var optVal = data.d[idx].RuleInfo;
                var tmpOptList = '<option value="' + optKey + '">' + optVal + '</option>';

                optList += tmpOptList;
            }
            //console.log(optList);
            $('#cbAddRules').html(optList);
        }
    });
    return false;
}

function cacheData(data) {
    var result = '<input type="hidden" id="txtCtrlEnd" name="txtCtrlEnd" value="' + data[0] + '" />' +
    '<input type="hidden" id="txtValEnd" name="txtValEnd" value="' + data[1] + '" />' +
    '<input type="hidden" id="txtValExtEnd" name="txtValExtEnd" value="' + data[2] + '" />' +
    '<input type="hidden" id="txtPathEnd" name="txtPathEnd" value="' + data[3] + '" />';

    return result;
}

function createLayers(layerNum) {
    var result = '<div class="rule-box">' +
       '     <div class="rule-content">' +
       '         <div class="rule-header-box">' +
       '             <div class="rule-header">Requester:</div>' +
       '             <div class="btnAdd btnSmall">Add</div>' +
       '             <select name="cbAdd" class="cbAdd">' +
       '                 <option value="1">Role</option>' +
       '                 <option value="2">Person</option>' +
       '             </select>' +
       '             <div class="cl_both"></div>' +
       '         </div>' +
       '         <div class="rule-list-box">' +
       '             <table class="tblstyle" style="margin-bottom:5px;padding-bottom:0;">' +
       '                 <thead>' +
       '                     <tr>' +
       '                         <th style="table-layout:fixed;width:60px;">Type</th>' +
       '                         <th>Name</th>' +
       '                         <th style="table-layout:fixed;width:30px;">Option</th>' +
       '                     </tr>' +
       '                 </thead>' +
       '                 <tbody>' +
       '                     <tr><td colspan="3">No data</td></tr>' +
       '                 </tbody>' +
       '             </table>' +
       '         </div>' +
       '     </div>' +
       '     <div class="ruleDown"></div>' +
       ' </div>';

    //var maxSteps = layerNum - 1;
    for (var idx = 0; idx < layerNum; idx++) {
        var iconArrow = (idx == (layerNum - 1)) ? ' style="display:none;"' : '';
        var keyLayer = (idx == 0) ? '' : '<div class="btnRemoveLayer btnSmall">Remove Layer</div>';
        //console.log("[" + idx + "] " + (idx + 1) + ": " + keyLayer);
        var tmpResult = '<div class="rule-box">' +
        '<div class="rule-content">' +
        '    <div class="rule-header-box">' +
        '        <div class="rule-header">Approval Layer : ' + (idx + 1) + '</div>' +
        '        <div class="btnAdd btnSmall">Add</div>' +
        '        <select name="cbAdd" class="cbAdd">' +
        '           <option value="1">Role</option>' +
        '            <option value="2">Person</option>' +
        '        </select>' +
        '        <div class="cl_both"></div>' +
        '    </div>' +
        '    <div class="rule-list-box">' +
        '        <table class="tblstyle" style="margin-bottom:5px;padding-bottom:0;">' +
        '            <thead>' +
        '                <tr>' +
        '                    <th style="table-layout:fixed;width:60px;">Type</th>' +
        '                    <th>Name</th>' +
        '                    <th style="table-layout:fixed;width:30px;">Option</th>' +
        '                </tr>' +
        '            </thead>' +
        '            <tbody>' +
        '                <tr><td colspan="3">No data</td></tr>' +
        '            </tbody>' +
        '        </table>' +
        '    </div>' + keyLayer +
        '</div>' +
        '<div class="ruleDown"' + iconArrow + '></div>' +
        '</div>';
        result += tmpResult;
    }
    
    return result;
}

function addLayer(LayerNum, isLast) {
    var iconArrow = (isLast == false) ? '' : ' style="display:none;"';
    var template = '<div class="rule-box">' +
        '<div class="rule-content">' +
        '    <div class="rule-header-box">' +
        '        <div class="rule-header">Approval Layer : ' + LayerNum + '</div>' +
        '        <div class="btnAdd btnSmall">Add</div>' +
        '        <select name="cbAdd" class="cbAdd">' +
        '           <option value="1">Role</option>' +
        '            <option value="2">Person</option>' +
        '        </select>' +
        '        <div class="cl_both"></div>' +
        '    </div>' +
        '    <div class="rule-list-box">' +
        '        <table class="tblstyle" style="margin-bottom:5px;padding-bottom:0;">' +
        '            <thead>' +
        '                <tr>' +
        '                    <th style="table-layout:fixed;width:60px;">Type</th>' +
        '                    <th>Name</th>' +
        '                    <th style="table-layout:fixed;width:30px;">Option</th>' +
        '                </tr>' +
        '            </thead>' +
        '            <tbody>' +
        '                <tr><td colspan="3">No data</td></tr>' +
        '            </tbody>' +
        '        </table>' +
        '    </div>' +
        '    <div class="btnRemoveLayer btnSmall">Remove Layer</div>' +
        '</div>' +
        '<div class="ruleDown"' + iconArrow + '></div>' +
        '</div>';
    return template;
}

function processJSON(response, sender) {
    var result = "";
    var dataLength = response.length;
    if (dataLength > 0) {
        var tdID = '<td style="table-layout:fixed;width:122px;">';
        var tdName = '<td style="table-layout:fixed;width:224px;">';
        var tdEnd = '</td>';
        for (var idx = 0; idx < dataLength; idx++) {
            var isOddorEven = (idx % 2 == 0) ? 'odd' : 'even';
            var isLastRow = (idx == (dataLength - 1)) ? 'border-bottom:1px solid #ccc;' : '';
            var tmpIDHide = "";
            var sentIDHide = "";
            if (!(response[idx].ID == null || typeof response[idx].ID == 'undefined' || response[idx].ID == '')) {
                tmpIDHide = '<span style="display:none;">' + response[idx].ID + '</span>';
                sentIDHide = response[idx].IDHide;
            }
            var addScript = ' onmouseover="this.style.background=\'#ccc\'" onMouseout="this.style.background=\'\'" ';
            var strID = response[idx].ID;
            var strData = "'" + strID + "','" + response[idx].Name + "'";
            var trStart = '<tr style="cursor:pointer;' + isLastRow + '" class="tRow ' + isOddorEven + '" onclick="insertRow(' +
                sender + ',' + strData + ');" ' + addScript + ' >';
            var trEnd = '</tr>';
            var tmpID = trStart + tdID + tmpIDHide + response[idx].Role + tdEnd;
            var tmpName = tdName + response[idx].Name + tdEnd + trEnd;

            result += tmpID + tmpName;
        }
    } else {
        result = '<tr><td colspan="2" style="padding:30px 10px; text-align:center; width:348px">Data not found</td></tr>';
    }
    return result;
}

function dialogForm(mode, sender, content) {
    var sMode = (typeof mode == 'undefined' || mode == '') ? '' : mode;
    var sContent = (typeof content == 'undefined' || content == '') ? '' : content;
    var sSender = (typeof sender == 'undefined' || sender == '') ? '0' : sender;
    var tblID = (sMode == '') ? 'tblUsers' : ((sMode == '2') ? 'tblUsers' : 'tblRoles');
    var search = '<div style="margin:5px 0;">' +
        '<input id="autocomplete1" type="text" placeholder="Type & Enter" value="" style="width:280px;" />' +
        '<div id="btnSearch" class="btnSmall">Search</div><span style="display:none;">' + sSender + '</span>' +
        '</div>';
    var tbl1 = '<table id="' + tblID + '" class="tblstyle" style="border:0; width:100%;">' +
            '<thead style="display:block;">' +
            '    <tr>' +
            '        <th style="table-layout: fixed; width:120px;">Role</th>' +
            '        <th style="table-layout: fixed; width:240px;">Name</th>' +
            '    </tr>' +
            '</thead>' +
            '<tbody style="display:block; height:240px; overflow-y:scroll;">';
    var tbl2 = '</tbody></table>';

    var result = tbl1 + search + sContent + tbl2;
    $('#ModalDialog').html(result);
}

function searchData(container, ctrlValue) {
    var findTbl = container.next();
    var idTbl = findTbl.attr("id");
    var postFncTo = (idTbl == 'tblRoles') ? 'LoadRole' : 'LoadUser';
    var postTo = 'AddRules.aspx/' + postFncTo;
    var thisVal = (typeof ctrlValue == 'undefined' || ctrlValue == '') ? '' : ctrlValue;
    var strData = '{"Search": "' + thisVal + '"}';
    var thisIndex = container.children().eq(2).text();
    var tblBody = findTbl.children('tbody');
    $.ajax({
        type: "POST",
        url: postTo,
        data: strData,
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            tblBody.html("");
            var content = processJSON(data.d, thisIndex);
            tblBody.html(content);
        }
    });
    return false;
}

function insertRow(sender, id, name) {
    var parentDiv = $('#rule-wrapper').children('.rule-box').eq(sender);
    var childDiv = parentDiv.children().find('table');
    var tblBody = childDiv.children('tbody');
    var tblRows = tblBody.children('tr');
    var tblRowsCount = tblRows.length;

    var isNoData = false;
    for (var idx = 0; idx < tblRowsCount; idx++) {
        var tblColCount = tblRows.eq(idx).children('td').length;
        if (tblColCount <= 1) {
            isNoData = true;
        }
    }

    var btnDel = '<img class="imgDel" src="images/delete.png" style="cursor:pointer;width:14px;height:14px;border:0;" title="Remove" />';
    var cbAdd = parentDiv.children().find('.cbAdd');
    var actCat = (cbAdd.val() == 1) ? "Role" : "Person";
    var tmpNewRow = '<td><span style="display:none">' + sender +
        '</span><span>' + actCat + '</span></td>' +
        '<td style="text-align:left;"><span style="display:none">' + id +
        '</span><span>' + name + '</span></td>' +
        '<td>' + btnDel + '</td></tr>';

    if (isNoData == true) {
        tblBody.html("");

        var tmpTRNew = '<tr class="odd">';
        var newRow = tmpTRNew + tmpNewRow;
        tblBody.html(newRow);
    } else {
        var isExist = false;
        var tblRowChilds = tblRows.children('td');
        for (var i = 0; i < tblRowsCount; i++) {
            var currentID = tblRows.eq(i).children('td').eq(1).children('span').eq(0).text();
            if (currentID == id) {
                isExist = true;
                break;
            }
        }

        if (!isExist) {
            var setClass = ((tblRowsCount % 2) == 0) ? 'odd' : 'even';
            var tmpTRNew = '<tr class="' + setClass + '">';
            var newRow = tmpTRNew + tmpNewRow;
            tblBody.append(newRow);
        } else {
            alert('Role and/or Person is already listed!');
        }
    }

    $('#ModalDialog').closeCZDialog();
}

function saveLayer(data) {
    var topParent = $('#rule-wrapper').children('.rule-box');
    var childLength = topParent.length;

    var tblInfo = $('#tblRuleInfo > tbody').children('tr');
    //var stepCategory = tblInfo.eq(2).children('td').eq(2).text();
    //var scenario = $('#cbBranch').val();
    var stepCategory = data[0];
    var ruleValue = data[1];
    var ruleValueExt = data[2];
    var scenario = data[3];
    

    var divParent = $('#rule-wrapper');
    var divRules = divParent.children();
    var divRulesLength = divRules.length;
    var divContent = divRules.children('.rule-content').children('.rule-list-box');
    var tblContent = divContent.children('table');
    var tblContentLength = divRules.length;

    var chkLength = tblContent.length;
    var isNotEmpty = true;
    for (var iXs1 = 0; iXs1 < chkLength; iXs1++) {
        var chkTbl = tblContent.eq(iXs1);
        var chkRows = chkTbl.children('tbody').children('tr');
        var chkRowLength = chkRows.length;
        for (var iXs2 = 0; iXs2 < chkRowLength; iXs2++) {
            var chkTD = chkRows.eq(iXs2).children('td').length;
            if (chkTD <= 1) {
                isNotEmpty = false;
                break;
            }
        }
    }

    if (isNotEmpty == true) {
        var _StepSeq = [];
        var _CurrentStep = [];
        var _NextStep = [];
        var _ActorCategory = [];
        for (var idx1 = 0; idx1 < tblContentLength; idx1++) {
            var tRow = tblContent.eq(idx1).children('tbody').children('tr');
            var tRowLength = tRow.length;

            _StepSeq[idx1] = [];
            _CurrentStep[idx1] = [];
            _NextStep[idx1] = [];
            _ActorCategory[idx1] = [];
            for (var idx2 = 0; idx2 < tRowLength; idx2++) {
                var tDval = tRow.eq(idx2).children('td');
                var stepVal = tDval.eq(1).children().eq(0).text();
            }

            var tblNext = tblContent.eq((idx1 + 1)).children('tbody');
            var tblNextRow = tblNext.children('tr');
            var tblNextRowLength = tblNextRow.length;
            if (idx1 < (tblContentLength - 1)) {
                for (var idx3 = 0; idx3 < tRowLength; idx3++) {
                    var tDPrev1 = tRow.eq(idx3).children('td');
                    for (var idx4 = 0; idx4 < tblNextRowLength; idx4++) {
                        var tDvalNext = tblNextRow.eq(idx4).children('td');
                        var tDnextVal = tDvalNext.eq(1).children().eq(0).text();
                        var prevVal1 = tDPrev1.eq(1).children().eq(0).text();
                        var nextVal = tDnextVal;
                        var tmpRolePrev1 = tDPrev1.eq(0).children().eq(1).text();
                        var sRolePrev1 = (tmpRolePrev1 == 'Role') ? 'ROLE' : 'UNAME';

                        _StepSeq[idx1].push((idx1 + 1));
                        _CurrentStep[idx1].push(prevVal1);
                        _NextStep[idx1].push(nextVal);
                        _ActorCategory[idx1].push(sRolePrev1);
                    }
                }
            } else if (idx1 == (tblContentLength - 1)) {
                for (var idx5 = 0; idx5 < tRowLength; idx5++) {
                    var tDPrev2 = tRow.eq(idx5).children('td');
                    var prevVal2 = tDPrev2.eq(1).children().eq(0).text();
                    var tmpRolePrev2 = tDPrev2.eq(0).children().eq(1).text();
                    var sRolePrev2 = (tmpRolePrev2 == 'Role') ? 'ROLE' : 'UNAME';
                    var lastStep = "0";

                    _StepSeq[idx1].push((idx1 + 1));
                    _CurrentStep[idx1].push(prevVal2);
                    _NextStep[idx1].push(lastStep);
                    _ActorCategory[idx1].push(sRolePrev2);
                }
            }
        }

        var data_RuleAlias = '{"RuleControl":"' + stepCategory + '", ';
        var data_RuleValue = '"RuleValue":"' + ruleValue + '", ';
        var data_RuleValueExt = '"RuleValueExt":"' + ruleValueExt + '", ';
        var data_Scenario = '"Scenario":"' + scenario + '", ';
        var data_StepSeq = '"StepSeq": ["' + _StepSeq + '"], ';
        var data_CurrentStep = '"CurrentStep": ["' + _CurrentStep + '"], ';
        var data_NextStep = '"NextStep": ["' + _NextStep + '"], ';
        var data_ActorCategory = '"ActorCategory": ["' + _ActorCategory + '"]}';

        var sendData = data_RuleAlias + data_RuleValue + data_RuleValueExt + data_Scenario +
                    data_StepSeq + data_CurrentStep + data_NextStep + data_ActorCategory;
        //var sendData = '{"RuleDetails": ["' + _StepCategory + '"],' + data_ActorCategory + '}';
        //console.log(sendData);
        updateLayer(sendData);
    } else {
        alert('Update failed: One or more layers are still empty!');
    }
}

function updateLayer(details) {
    $.ajax({
        type: "POST",
        url: "AddRules.aspx/UpdateLayer",
        data: details,
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            if (data.d == 'success') {
                alert("Update data success!");
                window.location.href = "ApprovalRule.aspx";
            } else {
                alert(data.d);
            }
        }
    });
    return false;
}